package com.sykj.cloud.auth.controller;

import com.sykj.cloud.auth.form.LoginBody;
import com.sykj.cloud.auth.service.MemberLoginService;
import com.sykj.cloud.common.core.domain.R;
import com.sykj.cloud.common.core.utils.StringUtils;
import com.sykj.cloud.common.core.web.domain.AjaxResult;
import com.sykj.cloud.common.security.service.MemberTokenService;
import com.sykj.cloud.system.api.domain.Member;
import com.sykj.cloud.system.api.model.LoginMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 */
@RestController
public class MemberTokenController {
    @Autowired
    private MemberTokenService memberTokenService;

    @Autowired
    private MemberLoginService memberLoginService;

    @PostMapping("memberLogin")
    public R<?> login(@RequestBody LoginBody form) {
        // 会员登录
        LoginMember loginMember = memberLoginService.memberLogin(form.getLoginName(), form.getPassword());
        // 获取登录token
        return R.ok(memberTokenService.createMemberToken(loginMember));
    }

    @PostMapping("memberRegister")
    public AjaxResult register(@RequestBody Member member) {
        return memberLoginService.register(member);
    }

    @DeleteMapping("memberLogout")
    public R<?> memberLogout(HttpServletRequest request) {
        LoginMember loginMember = memberTokenService.getLoginMember(request);
        if (StringUtils.isNotNull(loginMember)) {
            String loginName = loginMember.getLoginName();
            // 删除会员缓存记录
            memberTokenService.delLoginMember(loginMember.getToken());
            // 记录会员退出日志
            memberLoginService.memberLogout(loginName);
        }
        return R.ok();
    }

    @PostMapping("memberRefresh")
    public R<?> memberRefresh(HttpServletRequest request) {
        LoginMember LoginMember = memberTokenService.getLoginMember(request);
        if (StringUtils.isNotNull(LoginMember)) {
            // 刷新令牌有效期
            memberTokenService.refreshMemberToken(LoginMember);
            return R.ok();
        }
        return R.ok();
    }
}
